<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>
<body>
    <h2>WebSocket Example</h2>
    Welcome
    <br/>
    <input type="text" id="text" />
    <button onclick="send()">Send</button>
    <button onclick="closeWebSocket()">Close</button>
    <div id="message"></div>

    <script type="text/javascript">
        var websocket = null;

        // 检查当前浏览器是否支持 WebSocket
        if ('WebSocket' in window) {
            // 初始化 WebSocket 连接，请确保使用正确的 WebSocket URL
            websocket = new WebSocket("ws://localhost:8080/wsdemo");
        } else {
            alert('Not support websocket');
        }

        // 连接发生错误的回调方法
        websocket.onerror = function() {
            setMessageInnerHTML("Error: Connection failed.");
        };

        // 连接成功建立的回调方法
        websocket.onopen = function(event) {
            setMessageInnerHTML("Connection opened.");
        };

        // 接收到消息的回调方法
        websocket.onmessage = function(event) {
            setMessageInnerHTML("Received: " + event.data);
        };

        // 连接关闭的回调方法
        websocket.onclose = function() {
            setMessageInnerHTML("Connection closed.");
        };

        // 监听窗口关闭事件，当窗口关闭时，主动关闭 WebSocket 连接
        window.onbeforeunload = function() {
            websocket.close();
        };

        // 将消息显示在网页上
        function setMessageInnerHTML(innerHTML) {
            document.getElementById('message').innerHTML += innerHTML + '<br/>';
        }

        // 关闭连接
        function closeWebSocket() {
            websocket.close();
        }

        // 发送消息
        function send() {
            var message = document.getElementById('text').value;
            if (message && websocket.readyState === WebSocket.OPEN) {
                websocket.send(message);
                setMessageInnerHTML("Sent: " + message);
            } else {
                setMessageInnerHTML("Message not sent: WebSocket is not open or empty message.");
            }
        }
    </script>
</body>
</html>
